package cn.tedu.demo01wj.controller;

import cn.tedu.demo01wj.entity.User;
import cn.tedu.demo01wj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/check")
    public String check(String username){

        User user = mapper.check(username);
        if (user!=null){//查询到了代表存在了
            return "用户名已存在!";
        }
        return "用户名可用!";
    }
    @RequestMapping("/reg")
    public int reg(User user){
        User u = mapper.check(user.getUsername());
        if (u != null) {
            return 2;
            /*throw new SecurityException("手机号已被注册");*/
        }
       mapper.insert(user);
        return 1;//注册成功
    }

    @RequestMapping("login")
    public int login(User user,String rem,HttpSession session, HttpServletResponse response) {
        User u = mapper.check(user.getUsername());
        if(u!=null){
            if (u.getPassword().equals(user.getPassword())) {
                if(rem!=null){
                    Cookie c1 = new Cookie("username", user.getUsername());
                    Cookie c2 = new Cookie("password", user.getPassword());
                    //把Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //把登录成功的用户对象保存到会话对象
                session.setAttribute("user",u);
                return 1;
            }else {
                return 3;
            }
        }
        return 2;
    }
    @RequestMapping("/checkLogin")
    public User checkLogin(HttpSession session){
        //把登陆成功时保存的用户对象返回给客户端
        return (User) session.getAttribute("user");

    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {

        session.removeAttribute("user");

    }


}
